<?php

/**
 * ERP用户仓库
 * @author wangwx 2015-5-12
 */
namespace common\repositories\myhtsq;
use common\entities\myhtsq\ErpBusinessUnitEntity;
use common\entities\myhtsq\RoleUserEntity;
use common\repositories\BaseRepository;
use common\support\StringHelper;
use common\entities\myhtsq\ErpUserEntity;
use yii\db\Query;
use Yii;
class ErpUserRepository extends BaseRepository{

	/**
	 * 构造方法
	 * @param unknown $config (optional)
	 */
	public function __construct($config = [])
	{
		parent::__construct($config);
	}
	
	/**
	 * 根据关键字,搜索返回用户列表
	 * @param string $keyword 搜索关键字
	 * @param int $limit 返回条数
	 * @return array
	 */
	public static function getErpUserByKeyword($keyword, $limit = 10)
	{
		$query = (new Query())->from(ErpUserEntity::tableName())
				->select('ParentBU.BUCode,myscrm_erp_user.UserGUID,myscrm_erp_user.UserCode')
				->addSelect('myscrm_erp_user.UserName,myscrm_erp_user.BUGUID,myscrm_erp_user.DepartmentGUID')
				->addSelect('CompanyBu.BUName as CompanyName,DepartmentBu.BUName as DepartmentName')
				->addSelect('myscrm_erp_user.AbuName,myscrm_erp_user.AbuFzrName,myscrm_erp_user.DeptmentFzrName')
				->addSelect('myscrm_erp_user.MobilePhone,myscrm_erp_user.Email')
				->addSelect('myscrm_erp_user.AbuGUID,myscrm_erp_user.ABuFzrID,myscrm_erp_user.DeptmentFzrID')
				->leftJoin('myscrm_erp_business_unit ParentBU', 'ParentBU.BUGUID=myscrm_erp_user.ParentGUID')
				->leftJoin('myscrm_erp_business_unit CompanyBu', 'CompanyBu.BUGUID=myscrm_erp_user.BUGUID')
				->leftJoin('myscrm_erp_business_unit DepartmentBu', 'DepartmentBu.BUGUID=myscrm_erp_user.DepartmentGUID')
				->where(['myscrm_erp_user.IsDisabeld' => 0]);
		if (!empty($keyword)) {
			$query->andWhere(['like', 'myscrm_erp_user.UserName', $keyword]);
		}
		return $query->limit($limit)->all(ErpUserEntity::getDb());
	}
	
	
	/**
	 * 根据用户id,获取用户名称
	 * @param string $userGuid 用户guid
	 * @return string $userName 用户名称
	 */
	public static function getUserNameByBuguid($userGuid) {
		$res = ErpUserEntity::find()->select('UserName')->where(['UserGUID'=>$userGuid])->scalar();
        return empty($res) ? '' : $res;
	}

    /**
     * 根据用户id,获取用户名称
     * @param string $userGuids 用户guid
     * @return array
     */
    public static function getAllUserNameByUserGUIDs($userGuids) {
        return ErpUserEntity::find()
            ->select('UserName,UserGUID')
            ->where(['UserGUID' => $userGuids])
            ->asArray()
            ->all();
    }
        
    /**
    * 根据用户代码获取用户实体信息
    * @param string $usercode
    * @return ErpUserEntity
    */
	public static function getUserByCode($usercode) {
		return ErpUserEntity::find()->where(['UserCode'=>$usercode])->one();
	}	

    /**
    * 根据用户Id获取用户实体信息
    * @param string $userguid
    * @return ErpUserEntity
    */
	public static function getUserById($userguid) {
		return ErpUserEntity::find()->where(['UserGuid'=>$userguid])->one();
	}

	/**
	 * 根据用户Id获取用户实体信息
	 * @param string $userguid
	 * @return ErpUserEntity
	 */
	public static function getUserInfoById($userguid) {
		$query = (new Query())->from(ErpUserEntity::tableName())
			->select('ParentBU.BUCode,myscrm_erp_user.UserGUID,myscrm_erp_user.UserCode')
			->addSelect('myscrm_erp_user.UserName,myscrm_erp_user.BUGUID,myscrm_erp_user.DepartmentGUID')
			->addSelect('CompanyBu.BUName as CompanyName,DepartmentBu.BUName as DepartmentName')
			->addSelect('myscrm_erp_user.AbuName,myscrm_erp_user.AbuFzrName,myscrm_erp_user.DeptmentFzrName')
			->addSelect('myscrm_erp_user.AbuGUID,myscrm_erp_user.ABuFzrID,myscrm_erp_user.DeptmentFzrID')
			->leftJoin('myscrm_erp_business_unit ParentBU', 'ParentBU.BUGUID=myscrm_erp_user.ParentGUID')
			->leftJoin('myscrm_erp_business_unit CompanyBu', 'CompanyBu.BUGUID=myscrm_erp_user.BUGUID')
			->leftJoin('myscrm_erp_business_unit DepartmentBu', 'DepartmentBu.BUGUID=myscrm_erp_user.DepartmentGUID')
			->where(['myscrm_erp_user.IsDisabeld' => 0]);
		if (!empty($userguid)) {
			$query->andWhere(['myscrm_erp_user.UserGUID' => $userguid]);
		}
		return $query->one(ErpUserEntity::getDb());
	}
        
    /**
    * 根据用户代码和密码获取用户实体信息
    * @param string $usercode
    * @param string $password
    * @return ErpUserEntity
    */
	public static function getUserByCodeAndPassword($usercode,$password) {
		return ErpUserEntity::find()->where(['UserCode'=>$usercode,'Password'=>$password])->one();
	}

	public function getUserListByBuGUIDAndKeyword($buGUID, $keyword, $hasBindUserList = [])
	{
		$where = ['IsDisabeld' => 0];
		$andwhere = [];
		if (!empty($keyword)){
			$buGUID = [];
		}
		if (!empty($buGUID)){
			$where['BUGUID'] = $buGUID;
		}
		if (!empty($keyword)){
			$andwhere = ['like', 'UserName', $keyword];
		}

		return ErpUserEntity::find()
				->select('UserGUID,UserCode,UserName')
				->where($where)
				->andWhere($andwhere)
				->andFilterWhere(['not in', 'UserGUID',$hasBindUserList])
				->asArray()
				->all();
	}

	public function saveRoleUserBatch($role_id, $userList)
	{
//		$userList = json_decode($userList,true);
		RoleUserEntity::deleteAll(['role_id'=>$role_id]);
		$sql = '';
		$operateUser = Yii::$app->user->identity->username;
		foreach($userList as $k => $v){
			$sql .= "INSERT INTO myscrm_role_user (role_id,user_id,created_by,modified_by) VALUES($role_id,'".$v."','".$operateUser."','".$operateUser."'); ";
		}
		$connection = ErpUserEntity::getDb();
		return $connection->createCommand($sql)->execute();
	}

	public function getUserList($buGUID,$keyword, $perPage, $offset)
	{
		$where = ['eu.IsDisabeld' => 0];
		$andwhere = [];
		if (!empty($buGUID)){
			$where['eu.BUGUID'] = $buGUID;
		}
		if (!empty($keyword)){
			$andwhere = ['like', 'eu.UserName', $keyword];
		}

		$query = (new Query())->from(ErpUserEntity::tableName())
				->select('eu.UserGUID,eu.UserName,ebu.BUName,ebu.BUGUID')
				->from('myscrm_erp_user as eu')
				->leftJoin('myscrm_erp_business_unit as ebu','eu.BUGUID=ebu.BUGUID')
				->where($where)
				->andWhere($andwhere);
		$db = ErpUserEntity::getDb();
		$userList = $query->offset($offset)
				->limit($perPage)
				->all($db);
		$total = $query->count('*',$db);
		return ['userList' => $userList, 'pageTotal' => $total];

	}

	/**
	 * 获取用户信息（租户后台用户管理）
	 * @param $userGUID
	 */
	public function getUserInfo($userGUID)
	{
		$query = (new Query())->from(ErpUserEntity::tableName())
				->select('eu.UserGUID,eu.UserName,ebu.BUName,ebu.BUGUID,eu.MobilePhone')
				->from('myscrm_erp_user as eu')
				->leftJoin('myscrm_erp_business_unit as ebu','eu.BUGUID=ebu.BUGUID')
				->where(['UserGUID'=>$userGUID]);
		return $query->one(ErpUserEntity::getDb());
	}

    /**
     * 获取区域负责人，过滤掉已禁用的用户
     * @param $BUGUID
     * @return array
     */
    public function getAreaChargeList($BUGUID)
    {
        $query = (new Query())->from(ErpUserEntity::tableName())
            ->select(['eu.UserGUID', 'eu.UserName', 'eu.MobilePhone', 'eu.Email', 'eu.BUGUID', 'eu.DepartmentGUID', 'c.BUName as BUName', 'd.BUName as DepartmentName'])
            ->from('myscrm_erp_user as eu')
            ->leftJoin('myscrm_role_user as ru', 'eu.UserGUID=ru.user_id')
            ->leftJoin('myscrm_erp_business_unit as c', 'c.BUGUID=eu.BUGUID')
            ->leftJoin('myscrm_erp_business_unit as d', 'd.BUGUID=eu.DepartmentGUID')
            ->where([
                'eu.IsDisabeld' => 0,
                'eu.BUGUID'     => $BUGUID,
                'ru.role_id'    => 15,
            ])
            ->orderBy('ru.created_on DESC');

        return $query->all(ErpUserEntity::getDb());
    }

    /**
     * @param $buguid
     * @return array|null|ErpBusinessUnitEntity
     */
	public function getErpBusinessUnitByBuguid($buguid)
    {
        return ErpBusinessUnitEntity::find()
            ->where(['BUGUID' => $buguid])
            ->one();
    }

	/**
	 * 根据部门负责人ID查找人员GUID数组
	 * @param $deptmentFzrID
	 * @return array
	 */
	public static function getUserGuidsByDeptmentFzrID($deptmentFzrID)
	{
		$data = ErpUserEntity::find()->select("UserGUID")->where(["DeptmentFzrID" => $deptmentFzrID])->all();
		$res = [];
		foreach ($data as $item) {
			array_push($res, $item["UserGUID"]);
		}
		return $res;
	}


	public static function getUserGuidByUserName($userName){
        $result = ErpUserEntity::find()->select('UserGUID')
            ->where(['UserName' => $userName])
            ->one();
        return $result['UserGUID'];
    }
}